package com.bjpowernode.mvc.service.Impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.bjpowernode.common.consts.AppConst;
import com.bjpowernode.db.domain.AccountDetail;
import com.bjpowernode.db.domain.BidInfo;
import com.bjpowernode.db.domain.IncomeRecord;
import com.bjpowernode.db.domain.ProductInfo;
import com.bjpowernode.db.result.IncomeProductResult;
import com.bjpowernode.mvc.service.BaseService;
import com.bjpowernode.mvc.service.inter.IncomeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;


@Service
public class IncomeServiceImpl extends BaseService implements IncomeService {

    @Override
    public List<IncomeProductResult> queryMoreByUid(Integer userId, Integer pageNo, Integer pageSize) {

        int Offset = (pageNo - 1) * pageSize;
        List<IncomeProductResult> incomeList = incomeRecordMapper.selectIncomeByUid(userId, Offset, pageSize);

        return incomeList;
    }


    //收益计划.
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void generateIncomePlan() {

        //查询满标的产品
        Date date = new Date();
        DateTime yesterday = DateUtil.offsetDay(date, -1);
        DateTime beginTime = DateUtil.truncate(yesterday, DateField.DAY_OF_MONTH);
        DateTime endTime = DateUtil.truncate(date, DateField.DAY_OF_MONTH);
        List<ProductInfo> productInfoList = productInfoMapper.selectManBiaoProductList(beginTime, endTime);


        //查询每笔投资记录
        Date incomeDate = null,pullDateTime=null;
        BigDecimal dateRate = null,incomeMoney=null;
        Integer productType=-1,cycle=-1;
        for (ProductInfo manBiaoProduct : productInfoList) {

            //满标时间.
            pullDateTime=manBiaoProduct.getProductFullTime();

            //根据产品获取利率,周期,产品类型,等信息.
            cycle= manBiaoProduct.getCycle();
            dateRate = manBiaoProduct.getRate().divide(new BigDecimal("36000"), 9, RoundingMode.HALF_UP);

            List<BidInfo> bidList = bidInfoMapper.selectBidByProduct(manBiaoProduct.getId());

            //计算每个投资记录的利息和到期时间.
            for(BidInfo bid: bidList){
                if (productType == AppConst.TYPE_XIN_SAN_BTAO){
                    //周期是天.
                    incomeMoney = bid.getBidMoney().multiply(new BigDecimal(cycle)).multiply(dateRate);

                    incomeDate=DateUtil.offsetDay(pullDateTime,cycle);
                }else {
                    //周期是30天
                    incomeMoney=bid.getBidMoney().multiply(new BigDecimal(cycle*30)).multiply(dateRate);

                    incomeDate=DateUtil.offsetDay(pullDateTime,cycle*30);
                }

                //存储数据到b_income_record
                IncomeRecord record=new IncomeRecord();
                record.setUid(bid.getUid());
                record.setProdId(bid.getProdId());
                record.setBidId(bid.getId());
                record.setBidMoney(bid.getBidMoney());
                record.setIncomeDate(incomeDate);
                record.setIncomeMoney(incomeMoney);
                record.setIncomeStatus(AppConst.STATUS_INCONE_PALN);

                incomeRecordMapper.insert(record);

            }

            //修改理财产品的状态为2
            ProductInfo update=new ProductInfo();
            update.setId(manBiaoProduct.getId());
            update.setProductStatus(AppConst.STATUS_PRODUCT_INCOME_PLAN);

            int row=productInfoMapper.updateById(update);
            if (row<1){
                throw new RuntimeException("修改产品生成收益计划失败.");
            }
        }

        //

    }


    //收益返还.
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void generateIncomeBack() {

        //查询到期的收益记录.
        DateTime dateTime=DateUtil.truncate(DateUtil.yesterday(),DateField.DAY_OF_MONTH);
        List<IncomeRecord> incomeList=incomeRecordMapper.selectIncomeBackList(dateTime);

        //变量收益记录.
        int row=0;
        for (IncomeRecord income : incomeList) {
            row=accountMapper.addAvaiableMoney(income.getUid(),income.getBidMoney(),income.getIncomeMoney());
            if (row<1){
                throw new RuntimeException("收益返还,更新账户资金失败.");
            }

            //更新账户流水.
            AccountDetail accountDetail=new AccountDetail();
            accountDetail.setUid(income.getUid());
            accountDetail.setAction(AppConst.ADD);
            accountDetail.setActionTime(new Date());
            accountDetail.setMoney(income.getBidMoney());
            accountDetail.setMemo("收益返还本金:"+income.getBidMoney());
            accountDetailMapper.insert(accountDetail);


            accountDetail=new AccountDetail();
            accountDetail.setUid(income.getUid());
            accountDetail.setAction(AppConst.ADD);
            accountDetail.setActionTime(new Date());
            accountDetail.setMoney(income.getIncomeMoney());
            accountDetail.setMemo("收益返还利息:"+income.getIncomeMoney());
            accountDetailMapper.insert(accountDetail);


            //修改收益表的状态为1
            income.setIncomeStatus(AppConst.STATUS_INCOME_BACK);
            row=incomeRecordMapper.updateById(income);
            if (row<1){
                throw new RuntimeException("收益返还,更新收益记录状态为1失败");
            }

        }


    }
}
